<template>
  <div :class="{'opacity_panel': !showPanel}" class="audit_panel">
    <!--电核记录操作面板-->
    <h3 class="urging_panel_title">{{$t('tel.telRecord')}}</h3>
    <!--电核记录start-->
    <div class="audit_panel_module">
      <div class="panel_content">
        <p style="font-size: 14px;padding-bottom: 3px;">{{$t('tel.customerTel')}}:{{userData.phone}}<el-button :disabled="submitButt" @click="$call(userData.phone)" class="btn_call_center" size="mini" type="text" icon="el-icon-phone">Call</el-button><el-button @click="beforeSend(userData.phone)" :disabled="isDisabledSendMsg || !userData.phone" type="text" class="btn_send_msg">{{$t('xsDetails.sendMsg')}}</el-button></p>

        <!--风险提示start-->
        <div v-if="showPanel" class="audit_panel_module">
          <div class="audit_panel_module_title">{{$t('xsDetails.riskHint')}}</div>
          <div class="panel_content warning_tips">
            <el-row class="tips_row tips_row_title">
              <!--风险提示码-->
              <el-col class="tips_code" :span="6">{{$t('xsDetails.riskHintCode')}}</el-col>
              <!--风险提示类型-->
              <!--<el-col class="tips_type" :span="12">{{$t('xsDetails.riskHintType')}}</el-col>-->
              <!--展示-->
              <el-col class="tips_content" :span="6">{{$t('xsDetails.show')}}</el-col>
            </el-row>
            <el-row v-for="(item, $index) in riskList" :key="$index" class="tips_row">
              <el-col class="tips_code" :span="6">{{ item.code }}</el-col>
              <!--<el-col class="tips_type" :span="12">{{ $root.local === 'zhCN' ? item.text : item.indo }}&nbsp;</el-col>-->
              <el-col class="tips_content" :span="18">
                <template v-if="item.remarks && item.remarks.length > 0">
                  <template v-for="remark in item.remarks">
                    <span class="ml_10" v-if="item.code === 'R001'">{{ remark.userName }}</span>
                    <span class="ml_10" v-else-if="item.code === 'R002'">{{ remark.phone }}</span>
                    <template v-else-if="item.code === 'R010'">
                      <a class="ml_10" @click="goDetail(remark.userId)" v-if="remark.userName && remark.userId" href="javascript:void(0);">{{ remark.userName }}</a>
                      <span v-if="remark.userName && !remark.userId">{{ remark.userName }}</span>
                    </template>
                    <template v-else-if="item.code === 'R011'">
                      <a class="ml_10" @click="goDetail(remark.userId)" v-if="remark.userName && remark.userId" href="javascript:void(0);">{{ remark.userName }}<span v-if="remark.companyName">-{{ remark.companyName }}</span></a>
                      <span v-if="remark.userName && !remark.userId">{{ remark.userName }}<span v-if="remark.companyName">-{{ remark.companyName }}</span></span>
                    </template>
                    <template v-else-if="item.code === 'R012'">
                      <a class="ml_10" @click="goDetail(remark.userId)" v-if="remark.userName && remark.userId" href="javascript:void(0);">{{ remark.userName }}<span v-if="remark.phone">-{{ remark.phone }}</span></a>
                      <span v-if="remark.userName && !remark.userId">{{ remark.userName }}<span v-if="remark.phone">-{{ remark.phone }}</span></span>
                    </template>
                    <!--2-18-09-21新增风险提示码R016-->
                    <span class="ml_10" v-if="item.code === 'R016'">{{ remark.new_phone }}</span>
                    <!--END-->
                    <a class="ml_10" @click="goDetail(remark.userId)" v-else-if="remark.userName && remark.userId" href="javascript:void(0);">{{ remark.userName }}<span v-if="remark.companyName">-{{ remark.companyName }}</span></a>
                    <span v-else-if="remark.userName && !remark.userId">{{ remark.userName }}<span v-if="remark.companyName">-{{ remark.companyName }}</span></span>
                    <span v-else-if="remark.count"></span>
                    <span class="ml_10" v-else-if="item.code === 'K162'">{{ remark.msg }}</span>
                    <span class="ml_10" v-else-if="item.code === 'K163'">{{ remark.msg }}</span>
                    <span class="ml_10" v-else-if="item.code === 'K164'">{{ remark.msg }}</span>
                    <!--2018-09-21新增风险提示码K165-->
                    <span class="ml_10" v-else-if="item.code === 'K165'"></span>
                    <!--END-->
                  </template>
                </template>
                <span v-else-if="item.remarks.length === 0 && (item.code === 'R003' || item.code === 'R006')"></span>
                <span v-else-if="item.remarks.length === 0">--</span>
              </el-col>
            </el-row>
          </div>
        </div>
        <!--风险提示end-->

        <!--风险提示2-->
        <div v-if="showPanel" class="audit_panel_module">
          <div class="audit_panel_module_title">{{$t('xsDetails.riskTipsTwo')}}</div>
          <div class="panel_content warning_tips">
            <el-row class="tips_row tips_row_title">
              <!--风险提示代码-->
              <el-col class="tips_code" :span="10">{{$t('xsDetails.riskHintCode')}}</el-col>
              <!--展示-->
              <el-col class="tips_content" :span="14">{{$t('xsDetails.show')}}</el-col>
            </el-row>
            <el-row v-for="(item, $index) in riskTipsTwoNew" :key="$index" class="tips_row">
              <el-col class="tips_code" :span="10">{{ item.riskCode }}</el-col>
              <el-col class="tips_content" :span="14">{{ item.remarks }}</el-col>
            </el-row>
          </div>
        </div>
        <!--风险提示2 END-->

        <el-form :rules="formRules" ref="form" :model="form" label-position="top">
          <el-form-item label="电核结果" prop="verifyResult" :label="$t('tel.telResult')">
            <el-select :disabled="submitButt" v-model="form.verifyResult" @change="changeVal" :placeholder="$t('service.info.plsChoose')">
              <el-option v-if="!isNotMatch" key="0" label="待跟进" value="0" :label="$t('tel.willFollow')"></el-option>
              <el-option key="1" label="通过" value="1" :label="$t('xsDetails.pass')"></el-option>
              <el-option key="2" label="拒绝" value="2" :label="$t('xsDetails.refuse')"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="!isNotMatch" :label="$t('common.reason')" prop="reason">
            <el-select v-model="form.reason" placeholder="请选择" :placeholder="$t('service.info.plsChoose')" style="width: 100%;" :disabled="submitButt" >
              <el-option v-for="item in reasonlist" :key="item.dictCode" :value="item.dictCode" :label="item.dictCode + '-' + item.dictCodeNameReturn"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="isNotMatch && form.verifyResult" label="原因" :label="$t('tel.reason')">
            <span>{{ form.reason | reasonStatus }}</span>
          </el-form-item>
          <el-form-item v-if="!isNotMatch || (isNotMatch && form.verifyResult != 2)" label="备注" :label="$t('audit.remark')">
            <el-input :disabled="submitButt" v-model="form.remark" type="textarea" placeholder="请输入" :placeholder="$t('service.info.plsInput')" :maxlength="200" :rows="3"></el-input>
          </el-form-item>
          <el-form-item v-if="isNotMatch && form.verifyResult == 2" :label="$t('common.remark')" prop="remark">
            <el-input :disabled="submitButt" v-model="form.remark" type="textarea" placeholder="请输入" :placeholder="$t('service.info.plsInput')" :maxlength="200" :rows="3"></el-input>
          </el-form-item>
          <!--新增SPC码-->
          <el-form-item :label="$t('tel.spcCode')" prop="spcCode">
            <el-select v-model="form.spcCode" placeholder="请选择" :placeholder="$t('service.info.plsChoose')" style="width: 100%;" :disabled="submitButt" >
              <el-option v-for="item in SPCList" :key="item.dictCode" :value="item.dictCode" :label="item.dictCode + '-' + item.dictCodeNameReturn"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="form_btn">
            <el-button @click="goBack" type="primary" :disabled="submitButt" v-if="showGoBack&&markHistory&&!isNotMatch">{{$t('xsDetails.goBack')}}</el-button>
            <el-button @click="clear" type="primary" :disabled="submitButt">{{$t('common.clear')}}</el-button>
            <el-button @click="submitForm" type="primary" :disabled="submitButt">{{$t('service.info.submit')}}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <iframe :src="callSrc" width="0" height="0" style="opacity: 0;" frameborder="0"></iframe>
  </div>
</template>

<script>
  let that = null;
  import storage from '@/libs/storage';
  import EventBus from '@/libs/event-bus';
  import { eventConf } from '@/config/';

  export default {
    name: 'telOperationRecords',
    props: {
      showPanel: {
        type: Boolean,
        default: false
      },
      userData: {
        type: Object
      },
      isNotMatch: {
        type: Boolean
      }
    },
    data() {
      return {
        accountAnswer: '',
        callSrc: '',
        phoneAnswer: '',
        cardIdAnswer: '',
        bankAnswer: '',
        addressAnswer: '',
        contactsAnswer: '',
        companyNameAnswer: '',
        periodAnswer: '',
        amountAnswer: '',
        orderNid: '',
        selectNum: [],
        userId: '',
        user: storage.get('user'),
        reasonlist: [],
        submitButt: false,
        form: {
          verifyResult: '',
          reason: '',
          remark: '',
          spcCode: [],
        },
        verifyResult: '',
        formRules: {
          verifyResult: [
            { required: true, message: this.$t('tel.chooseTelResult') }
          ],
          reason: [
            { required: true, message: this.$t('tel.chooseReason') }
          ],
          remark: [
            { required: true, message: this.$t('tel.chooseRemark') }
          ]
        },
        SPCList: [],
        dictType: '',
        changeFlag: false,
        isDisabledSendMsg: false,
        markHistory: false,
        riskAllList: [],
        riskList: [], // 风险提示列表
        riskTipsTwoNew: [],
      };
    },
    computed: {
      // 后退按钮资源展示
      showGoBack() {
        return this.$store.getters.checkUserAuthority('/telDetailGoBack');
      },
    },
    watch: {
      'form.verifyResult': function(val) {
        if (this.form.verifyResult === '1') {
          this.dictType = 'SuccessCode';
        } else if (this.form.verifyResult === '2') {
          this.dictType = 'RefuseCode';
        } else if (this.form.verifyResult === '0') {
          this.dictType = 'WaitCode';
        } else {
          this.dictType = 1;
        }
        this.queryTelCode();
      },
    },
    methods: {
      // 获取原因码
      queryTelCode() {
        const params = {
          language: storage.getLocal('language'),
          dictType: this.dictType,
        };
        this.reasonlist = [];
        this.$api.tel.queryTelCode(params).then((res) => {
          const { status, data, error } = res;
          if ('1' === status && error === '00000000') {
            this.reasonlist = data;
          }
        });
      },
      // 获取订单状态
      getOrderInfo() {
        this.$api.tel.getOrderInfo({ orderNid: this.orderNid }).then((res) => {
          const { status, data, error } = res;
          if ('1' === status && error === '00000000') {
            this.orderStatus = data[0].checkStatus;
            if (this.orderStatus !== '1') {
              this.submitButt = true;
              EventBus.$emit('myparam', this.orderStatus);
            }
          }
        });
      },
      // 获取电核SPC码
      queryTelSpcCode() {
        const params = {
          language: storage.getLocal('language'),
          dictType: 'SpcCode',
        };
        this.$api.tel.queryTelCode(params).then((res) => {
          const { status, data, error } = res;
          if ('1' === status && error === '00000000') {
            this.SPCList = data;
          }
        });
      },
      // 提交
      submitForm() {
        if (this.isNotMatch && this.form.verifyResult == 2 && !this.form.remark) {
          this.$message.error(this.$t('tel.chooseRemark'));
          return;
        }
        this.$refs.form.validate((val) => {
          if (val) {
            const params = {
              userId: this.userId,
              orderNid: this.orderNid,
              language: storage.getLocal('language'),
              operPeopleId: this.operPeopleId,
              loginId: this.user.id,
              remark: this.form.remark,
              verifyResult: this.form.verifyResult,
              spcCode: this.form.spcCode,
              reasonList: [this.form.reason],
            };
            this.$api.tel.addVerifyRecords(params).then((res) => {
              const { status, data, error } = res;
              if ('1' === status && error === '00000000') {
                this.$message.success(this.$t('p2p.submitSucc'));
                this.queryRollbackOrder();
                this.clear();
                this.$emit('updateTable', 'hisTelRecord');
                EventBus.$emit(eventConf.UPDATATELRECORD);
                this.getOrderInfo();
              }
            });
          }
        });
      //  提交用户信息
        const params1 = {
          orderNid: this.orderNid,  // 订单号
          operPeopleId: this.operPeopleId,  // 操作人员Id
          phoneAnswer: this.phoneAnswer,  // 电话答案
          cardIdAnswer: this.cardIdAnswer,  // 身份证答案
          // 4个反欺诈问题
          bankAnswer: this.bankAnswer,  // 开户银行答案
          addressAnswer: this.addressAnswer,  // 居住地址
          contactsAnswer: this.contactsAnswer,  // 联系人姓名
          companyNameAnswer: this.companyNameAnswer,  // 工作单位
          periodAnswer: this.periodAnswer,  // 借款周期
          amountAnswer: this.amountAnswer,  // 借款金额
          answerRankList: this.answerRank,  // 反欺诈排序 "userForm.bankAnswer", "userForm.addressAnswer", "userForm.contactsAnswer", "userForm.companyNameAnswer"
          accountAnswer: this.accountAnswer,  // 收款账户信息是否一致 1-正确 2-错误
          otherAnswer: this.otherAnswer  //  {"whatsApp":"1","otherApp":"1"}
        };
        this.$api.tel.insertTelAnswer(params1).then((res) => {
          const { status, data } = res;
          if (status === '1') {
            //
          }
        });
      },
      clear() {
        this.form = {
          verifyResult: '',
          reason: '',
          remark: '',
          spcCode: '',
        };
      },
      // 回退
      goBack() {
        this.$confirm(this.$t('tel.goBackTips'), this.$t('activity.tips'), {
          confirmButtonText: this.$t('header.confirm'),
          cancelButtonText: this.$t('header.cancel'),
          // type: 'warning'
        }).then(() => {
          this.$api.tel.queryRollbackOrder({ orderId: this.orderNid }).then((res) => {
            const { status, data, error } = res;
            if (status === '1' && error === '00000000') {
              this.markHistory = data.mark !== '0';// mark '0'-已做回退 '1'-未做回退
              if (data.mark === '0') {
                this.$message({
                  type: 'success',
                  message: this.$t('tel.goBackTips2')
                });
              } else {
                this.orderRollback();
              }
            }
          });
          // this.$message({
          //   type: 'success',
          //   message: '删除成功!'
          // });
        }).catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // });
        });
      },
      orderRollback() {
        this.$api.tel.orderRollback({ orderId: this.orderNid }).then((res) => {
          const { status, data, error } = res;
          if (status === '1' && error === '00000000') {
            this.$message.success(this.$t('addCredit.operSuccess'));
            this.queryRollbackOrder();
            this.clear();
            this.getOrderInfo();
          }
        });
      },
      // 调呼叫系统
      callSystem(phone) {
        if (phone && /^\d+$/.test(phone)) {
          this.callSrc = `./static/dial.html?phone=${phone}&method=dial&timestamp=${Date.now()}`;
        }
        // const params = {
        //   orderId: this.orderNid,
        //   phone: this.userData.phone,
        //   loginName: this.user.username,
        // };
        // console.log(params)
      },
      listenEvent() {
        EventBus.$on('myParams1', (msg) => {
          this.phoneAnswer = msg;
        });
        EventBus.$on('myParams2', (msg) => {
          this.cardIdAnswer = msg;
        });
        EventBus.$on('myParams3', (msg) => {
          this.bankAnswer = msg;
        });
        EventBus.$on('myParams4', (msg) => {
          this.addressAnswer = msg;
        });
        EventBus.$on('myParams5', (msg) => {
          this.contactsAnswer = msg;
        });
        EventBus.$on('myParams6', (msg) => {
          this.companyNameAnswer = msg;
        });
        EventBus.$on('myParams7', (msg) => {
          this.periodAnswer = msg;
        });
        EventBus.$on('myParams8', (msg) => {
          this.amountAnswer = msg;
        });
        EventBus.$on('myParams9', (msg) => {
          this.answerRank = msg;
        });
        EventBus.$on('myParams10', (msg) => {
          this.accountAnswer = msg;
        });
        EventBus.$on('otherAnswerTel', (msg) => {
          this.otherAnswer = msg;
        });
      },
      changeVal(val) {
        if (this.changeFlag) {
          this.form.reason = '';
        } else {
          this.changeFlag = true;
        }
        if (this.isNotMatch && val) {
          this.$refs.form.clearValidate();
          this.form.reason = (this.form.verifyResult == 1) ? 'SC0001' : 'SC0002';
        }
      },
      beforeSend(phone) {
        const params = {
          orderNid: this.orderNid,
        };
        this.isDisabledSendMsg = true;
        this.$api.audit.queryOrderSendMessageMark(params).then((res) => {
          const { status, msg, data, error } = res;
          if ('1' === status && '00000000' === error && data) {
            if (data.remark == 1) {
              this.sendMsg(phone);
            } else {
              this.isDisabledSendMsg = false;
              this.$message.error(this.$t('xsDetails.canNotSendMsg'));
            }
          } else {
            this.isDisabledSendMsg = false;
            this.$message.error(msg);
          }
        });
      },
      markSend() {
        const params = {
          orderNid: this.orderNid,
        };
        this.$api.audit.addOrderSendMessageMark(params).then((res) => {
          this.isDisabledSendMsg = false;
          const { status, error } = res;
          if ('1' === status && '00000000' === error) {}
        });
      },
      // 发送短信
      sendMsg(phone) {
        const params = {
          phone,
          nid: 'indonesia_audit_notice_template'
        };
        this.$api.smsServer.send(params).then((res) => {
          const { status, msg, error } = res;
          if ('1' === status && '00000000' === error) {
            this.markSend();
            this.$message.success(this.$t('addCredit.operSuccess'));
          } else {
            this.isDisabledSendMsg = false;
            this.$message.error(msg);
          }
        });
      },
      queryRollbackOrder() {
        // 电核订单回详情查询
        this.$api.tel.queryRollbackOrder({ orderId: this.orderNid }).then((res) => {
          const { status, data, error } = res;
          if (status === '1' && error === '00000000') {
            this.markHistory = data.mark !== '0';// mark '0'-已做回退 '1'-未做回退
          }
        });
      },
      queryRiskCode() {
        // 电核查询rca风险提示码
        this.$api.tel.queryRiskCode({ orderNid: this.orderNid }).then((res) => {
          const { status, data, error } = res;
          if (status === '1' && error === '00000000') {
            if (data.risks && data.risks instanceof Array) {
              this.riskAllList.forEach((risk) => {
                data.risks.forEach((item) => {
                  if (risk.code === item.policyNumber && item.remarks) {
                    try {
                      let riskAll = null;
                      let hasRisk = false;
                      this.riskList.forEach((riskItem) => {
                        if (riskItem.code === risk.code) {
                          hasRisk = true;
                          riskAll = riskItem;
                        }
                      });
                      if (!hasRisk) {
                        riskAll = Object.assign({}, risk);
                      }
                      if (item.remarks.indexOf('"[') === 0 && item.remarks.indexOf(']"') > -1) {
                        item.remarks = item.remarks.substr(1, item.remarks.length - 2);
                      }
                      if (item.remarks.indexOf('\\') > -1) {
                        item.remarks = item.remarks.replace(/\\/g, '');
                      }
                      const marks = JSON.parse(item.remarks);
                      if (marks instanceof Array) {
                        marks.forEach((mark) => {
                          riskAll.remarks.push(mark);
                        });
                      } else if (typeof marks === 'object') {
                        riskAll.remarks.push(JSON.parse(item.remarks));
                      }
                      if (!hasRisk) {
                        this.riskList.push(riskAll);
                      }
                    } catch (e) {
                      console.log(e);
                      console.log(item);
                    }
                  } else if (risk.code === item.policyNumber && item.remarks === '') {
                    this.riskList.push(Object.assign({}, risk));
                  }
                });
              });
            }

          // this.riskTipsTwo = data;
          //  匹配
            if (data.newRisks && data.newRisks instanceof Array) {
              this.riskAllList.forEach((risk) => {
                data.newRisks.forEach((item) => {
                  if (item.riskCode === risk.code) {
                    this.riskTipsTwoNew.push(item);
                  }
                });
              });
            }
          }
        });
      },
      // 查询信审结论
      getReasonList() {
        this.$api.audit.rejectCode({ orderNid: this.orderId }).then((res) => {
          const { status, data, error } = res;
          if ('1' === status && error === '00000000') {
            if (data.riskCode && data.riskCode instanceof Array) {
              data.riskCode.forEach((item) => {
                item.remarks = [];
                this.riskAllList.push(item);
              });
            }
            this.queryRiskCode();
          }
        });
      },
    },
    created() {
      that = this;
      if (this.showPanel) {
        const params = this.$route.params;
        if (params.orderId) {
          this.orderNid = params.orderId;
          this.userId = params.id;
          this.operPeopleId = params.operPeopleId;
          this.getOrderInfo();
          this.listenEvent();
          this.queryRollbackOrder();
          this.getReasonList();
        }
        this.queryTelSpcCode();
      }
    },
    filters: {
//        不匹配订单原因
      reasonStatus(reason) {
        switch (reason) {
          case 'SC0001':
            return that.$t('tel.nameMatch');
          case 'SC0002':
            return that.$t('tel.nameNotMatch');
          default :
            return '--';
        }
      },
    }
  };
</script>

<style lang="scss" scoped>
  @import "~@/assets/scss/function";
  .audit_panel{
    /*padding: 0 16px;*/
  }
  .opacity_panel{
    opacity: 0.6;
  }
  .urging_panel_title{
    height: 52px;
    line-height: 52px;
    background-image: url("~@/assets/img/icon_edit.png");
    background-size: 20px 20px;
    background-repeat: no-repeat;
    background-position: left center;
    padding-left: 32px;
    border-bottom: 1px solid #d4d7da;
    margin: 0 16px;
  }
  .audit_panel_module{
    margin: 20px 0 30px;
  }
  .audit_panel_module_title{
    padding-left: 16px;
    border-left: 2px solid $primary;
    margin-bottom: 12px;
  }
  .panel_content{
    padding: 0 16px;
    font-size: 12px;
  }
  .tips_row{
    margin-top: 12px;
    color: #a6a8aa;
  }
  .tips_row_title{
    color: $colorText;
  }
  .tips_code, .tips_type{
    padding-right: 5px;
  }
  .form_btn{
    text-align: right;
  }
  .conclusion_radio{
    text-align: right;
  }

  .iconLeft {
    margin-left: 10px;
    border-radius: 15px;
  }
  .btn_send_msg {
    margin:0 0 0 10px;
  }
</style>
